import { defineStore } from 'pinia'
import { login, updateUserAvatarApi } from '@/api/auth'

import { parseJwt } from '@/utils/jwtUtils'
import { startHeartbeat,stopHeartbeat } from '@/utils/heartbeat'


interface UserState {
  token: string
  name: string
  roles: string[],
  avatar: string,
  isLoggedIn: boolean,
}



export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    token: localStorage.getItem('exam-token') || '',
    name: '',
    roles: [],
    avatar: '',
    isLoggedIn: false,
  }),
  actions: {
    async login(userInfo: { username: string; password: string }) {
      const res = await login(userInfo)
      const { code, data } = res
      if(code===1){
         this.token = data
        // 解析jwt
        const info = parseJwt(data)
        // 获取用户信息
        const {realName,avatar,roleId} = JSON.parse(info.userInfo)
        // 保存用户姓名到pinia中
        this.name = decodeURIComponent(escape(realName));
        // 保存用户头像到pinia中
        this.avatar = avatar
        this.isLoggedIn = true
        // 启用心跳
        startHeartbeat()
        
        // 根据角色 ID 设置角色
        switch (roleId) {
          case 1:
            // 学生角色
            this.roles.push('student')
            break
          case 2:
            // 老师角色
            this.roles.push('teacher')
            break
          case 3:
            // 管理员角色  
            this.roles.push('admin')
            break
          default:
            console.warn('未知的角色 ID:', roleId)
        }

      }
      return res
    },
    async getUserInfo() {
     // const userInfo = await getTokenInfo()
      //console.log('getUserInfo---------------:',userInfo.id)
      //const { data } = await getUserInfo(userInfo.id)
      
      //this.name = data.name
      //this.roles = data.roles
      //return data
    },
    resetToken() {
      this.token = ''
      this.roles = []
      localStorage.removeItem('exam-token')
    },
    setToken(token: string) {
      this.token = token
    },
    async updateAvatar(avatar: string)  {
      this.avatar = avatar
      //  保存用户头像到数据库中
      await updateUserAvatarApi(avatar)

    },
    async logout() {
      this.resetToken()
      this.isLoggedIn = false
      // 停止心跳
      stopHeartbeat()
    }
  },
  persist: {
    // 持久化key名称
    key: 'exam-token',
    // 只持久化token字段
    paths: ['token']
  }
})